import { reqLogin } from "@/api/reqUser"
import { permissions } from "@/config/permission"
import type { MENU } from "@/types/permission"
import type { LoginForm, USER } from "@/types/user"
import { defineStore } from "pinia"
import { computed, ref } from "vue"

export const useUserStore = defineStore("user", function () {
  // 定义一个用户对象
  // const user = ref({})
  const u = JSON.parse(localStorage.getItem("vue3-token") || "{}") as USER
  const user = ref<USER>(u)
  //   const user1 = reactive({})
  //  向外暴漏登录方法
  const loginFn = async (loginform: LoginForm) => {
    const res = await reqLogin(loginform) // Promise对象 成功太：
    if (res.status === 0) {
      user.value = res.data
      // 本地存储token 方便后续用户验证
      localStorage.setItem("vue3-token", JSON.stringify(user.value))
      return "登录成功"
    } else {
      // 返回一个失败状态Promise 值为 res.msg
      return Promise.reject(res.msg)
    }
  }
  // 用户的menus
  const menus = computed<string[] | undefined>(() => {
    return user.value.role?.menus
  })

  // 根据用户的menus 生成页面对应的menus
  const menuList = computed(() => {
    return filter(menus.value || [], permissions)
  })

  // 利用menus 在  permission中去筛选
  const filter = (menus: string[], permission: MENU[]) => {
    const resMenu: MENU[] = []
    for (let i = 0; i < permission.length; i++) {
      const m = permission[i]
      if (m.isPublic) {
        resMenu.push(m)
      }
      // m.index 在 menus里面
      // menux.indexOf(m.index) !== -1
      if (menus.includes(m.index)) {
        resMenu.push(m)
      }
      if (m.children) {
        const c = filter(menus, m.children)
        if (c.length > 0) {
          resMenu.push({
            ...m,
            children: c,
          })
        }
      }
    }

    return resMenu
  }

  // menus 在 permissions中筛选
  // [/user. /role, /student]
  /*
   [
  {
    title: "用户管理",
    icon: "UserFilled",
    index: "/user",
  },
  {
    title: "角色管理",
    icon: "WalletFilled",
    index: "/role",
  },
  {
    title: "学员管理",
    icon: "Avatar",
    index: "4",
    children: [
      {
        title: "学生管理",
        icon: "Stamp",
        index: "/student",
      },
    ],
    ]
  
  */
  return {
    user,
    loginFn,
    menuList,
    menus,
  }
})
